#include"ServerSocket.h"
#include"SocketException.h"
#include<string>
#include<iostream>
#include<thread>
#include<vector>
#include<signal.h>

using namespace std;

//vector<ServerSocket *>ServerVec;
//vector<thread *>ThreadVec;

void handle_client(ServerSocket *new_sock) {
	cout << "handle_client called" << endl;
	try {
        string data;
		while(true) {
			*new_sock >> data;
            cout << "client:" << data << endl;
            data.insert(0,"server send you ");
			*new_sock  << data;
			if (data == "quit") {
				cout << "%%" << endl;
				break;
			}
		}
	}
	catch(SocketException &e) {}
}
/*
void my_handler(int s) {
	cout << "caught signal " << s << endl;
	for (vector<thread *>::iterator it = ThreadVec.begin(); it != ThreadVec.end(); ++it) {
		cout << "##" << endl;
		delete (*it);
	}
	for (vector<ServerSocket *>::iterator it = ServerVec.begin(); it != ServerVec.end(); ++it) {
		cout << "**" << endl;
		delete (*it);
	}
}
*/
int main ( int argc, char *argv[] )
{
	/************************************
	 * 中断信号处理
	 * *********************************/
	/*struct sigaction sigIntHandler;
	sigIntHandler.sa_handler = my_handler;
	sigemptyset(&sigIntHandler.sa_mask);
	sigIntHandler.sa_flags = 0;
	sigaction(SIGINT, &sigIntHandler, NULL);*/
	cout << "running....\n";
	try
    {
		// Create the socket
		ServerSocket server ( 30000 );

		while ( true )
		{
			ServerSocket *new_sock = new ServerSocket();
			//ServerVec.push_back(new_sock);
			server.accept ( *new_sock );
			thread *client_thread = new thread(handle_client,new_sock);
			//detach将线程对象和线程执行的事例分离，执行部分结束后释放分配的资源
			client_thread->detach();
			//ThreadVec.push_back(client_thread);
			delete client_thread;
			cout << "thread id: " << client_thread->get_id() << endl;
		}
    }
	catch ( SocketException& e )
	{
		cout << "Exception was caught:" << e.description() << "\nExiting.\n";
    }
	cout << "yunxing" << endl;

	return 0;
}